package com.tangdi.production.mpaychl.controller.third;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.tangdi.production.mpaychl.service.impl.bailian.util.EnvironmentConstants;
import com.tangdi.production.mpaychl.service.impl.bailian.util.SecureUtil;
import com.tangdi.production.mpbase.constants.ExcepCode;
import com.tangdi.production.mpbase.constants.MsgCT;
import com.tangdi.production.mpbase.exception.BusinessException;
import com.tangdi.production.mpbase.service.OrderService;
import com.tangdi.production.mpbase.util.MoneyUtils;
import com.tangdi.production.mpbase.util.ObjectUtil;
import com.tangdi.production.mpbase.util.RequestUtil;

@Controller
public class BailianPayController {
	private static final Logger logger = LoggerFactory.getLogger(BailianPayController.class);
	
	@Autowired
	private OrderService orderService;
	
	@RequestMapping(value="bailianpay/notify")
	@ResponseBody
	public String payCallBack(HttpServletRequest request,HttpServletResponse response) throws Exception{
		//获取请求参数列表
		logger.info("进入【bailianpay】【支付回调】...");
		try {
			logger.info("异步返回数据:{}",JSON.toJSONString(request.getParameterMap()));
			logger.info("数据头:{}",JSON.toJSONString(request.getHeaderNames()));
			
			Map<String, Object> paramMap = RequestUtil.getReqMap(request);
			logger.info("[bailianpay]支付回调:" + paramMap);
			if(paramMap == null || paramMap.isEmpty()){
				throw new BusinessException("异步返回内容为空");
			}
			
			//渠道签名
			SecureUtil.decryptTradeInfo(EnvironmentConstants.MERCHANT_NO, "" + paramMap.get("CER"), "" + paramMap.get("DATA"), "" + paramMap.get("SIGN"), EnvironmentConstants.private_key, EnvironmentConstants.public_key);
			
			//订单号
			String prdOrdNo = (String) paramMap.get("outTradeNo");
			if(StringUtils.isEmpty(prdOrdNo)){
				throw new BusinessException(ExcepCode.EX900000,"回调订单号为空");
			}
			
			Map<String,Object> queryMap = new HashMap<String,Object>();
			queryMap.put("prdOrdNo", prdOrdNo);
			Map<String,Object> prdOrdMap = orderService.getPrdOrdMap(queryMap);
			
			String ordStatus = (String)prdOrdMap.get("ordStatus");
			if(MsgCT.ORDSTATUS_SUCCESS.equals(ordStatus)){//成功的订单不允许再更新
				logger.warn("订单状态已成功，不允许更新...");
				returnSuccess(response);
				return null;
			}
			
			String chlPayAmt = ObjectUtil.getString(paramMap.get("tradeAmount"));
			if(!chlPayAmt.equals(prdOrdMap.get("txAmt").toString())){
				throw new BusinessException(ExcepCode.EX900000,"支付金额不一致 成功金额[{}] 订单支付金额[{}]",chlPayAmt,prdOrdMap.get("txAmt").toString());
			}
			
			//原交易大商户编号
			String mchNo = (String) prdOrdMap.get("TMERCID");
			if(StringUtils.isEmpty(mchNo)){
				throw new BusinessException(ExcepCode.EX900000,"原交易商户号不能为空");
			}
			
			// 根据渠道号 商户号获得商户密钥
			queryMap.clear();
			queryMap.put("orgNo", prdOrdMap.get("payChannel"));//交易渠道编号
			queryMap.put("routeMerId", mchNo);//渠道商户编号
			List<Map<String,Object>> routeList = orderService.getOrgInfo(queryMap);
			if(routeList == null || routeList.isEmpty()){
				throw new BusinessException(ExcepCode.EX900001,"路由查询为空");
			}

			//定义回调订单信息Map
			Map<String,Object> orderCallBackMap = new HashMap<String, Object>();
			orderCallBackMap.put("prdOrdNo", prdOrdMap.get("prdOrdNo"));//订单号
			orderCallBackMap.put("ordStatus", MsgCT.ORDSTATUS_PROCESSING);
			orderCallBackMap.put("resJson", com.acq.sdk.JsonUtil.toJson(paramMap));
			String status = ObjectUtil.getString(paramMap.get("trade_status"));
			
			// 判断订单状态
			if ("S".equals(status)) {//支付成功
				orderCallBackMap.put("ordStatus", MsgCT.ORDSTATUS_SUCCESS);
			}
			else if ("F".equals(status)){
				orderCallBackMap.put("ordStatus", MsgCT.ORDSTATUS_FAIL);
			}
			else{//其他情况不处理
				logger.warn("回调状态不明确,不处理...");
				returnFailure(response);
				return null;
			}
			
			// 调用回调更新订单
			logger.info("通知平台更新订单[{}]", orderCallBackMap);
			orderService.prdPayCallBack(orderCallBackMap);
		}catch (Exception e) {
			logger.error("【bailianpay】【消费回调】失败：{}", e.getMessage(),e);
			returnFailure(response);
			return null;
		}
		logger.info("【bailianpay】【消费回调】完成" );
		returnSuccess(response);
		return null;
	}
	
	@RequestMapping(value="bailianpay/return")
	public String payReturn(HttpServletRequest request,HttpServletResponse response) throws Exception{
		logger.info("进入【bailianpay】【支付同步通知】...");
		Map<String, Object> paramMap = RequestUtil.getReqMap(request);
		logger.info("[bailianpay]支付同步通知:{}", paramMap);

		logger.info("【bailianpay】【支付同步通知】完成" );
		returnSuccess(response);
		return "";
	}
	
	/**
	 * 返回成功
	 * 
	 * @param response
	 * @param obj
	 * @throws Exception
	 */
	private void returnSuccess(HttpServletResponse response) throws Exception {
		respContent(response, "success");
	}

	/**
	 * 返回失败
	 * 
	 * @param response
	 * @param obj
	 * @throws Exception
	 */
	private void returnFailure(HttpServletResponse response) throws Exception {
		respContent(response, "failure");
	}

	private void respContent(HttpServletResponse response, String content)
			throws Exception {
		PrintWriter out = response.getWriter();
		out.write(content);
		out.flush();
		out.close();
	}
	
}
